package utility;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;

import javax.swing.ImageIcon;

public class IconHolder {

	protected HashMap<String, ImageIcon> imageContainer;
	public static IconHolder iconHolder;
	private static final String IMAGENDING = ".png";
	private static final String LOCATION = ".";

	/**
	 * Private constructor which loads all images.
	 * Loops through and picks up all images from given position.
	 */
	private IconHolder() {
		try {
			imageContainer = new HashMap<String, ImageIcon>();
			final File folder = new File((getClass().getClassLoader()).getResource(
					LOCATION).toURI()); //TODO: Will have to be changed when we use .jar file.
			for (final File f : folder.listFiles()) {
				if (f.getName().contains(IMAGENDING)) {
					imageContainer.put(f.getName().split("\\.")[0],
							fetchIcon(f.getName()));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * getInstance() returns an instance of the IconHolder singelton.
	 * @return an singelton of IconHolder.
	 */
	public static IconHolder getInstance() {
		if (iconHolder == null) {
			iconHolder = new IconHolder();
		}
		return iconHolder;
	}

	/**
	 * get the icon with the given name from the older.
	 * @param name is the name of the icon be retrieved.
	 * @return ImageIcon with given name from the holder.
	 */
	public synchronized ImageIcon getIcon(String name) {
		return imageContainer.get(name);
	}

	/**
	 * fetch the icon with a given text 
	 * @param text is the name of the ImageIcon to be fetched.
	 * @return the ImageIcon containing the Image with the given name that is loaded from the computer, or null if name isn't correct.
	 */
	public ImageIcon fetchIcon(String name) {
		if (name.length() > 4) {
			return new ImageIcon(
					(getClass().getClassLoader()).getResource(name));
		} else {
			System.out.println("NULL IN IconHolder, " + name);
			return null;
		}
	}


}